/********************************************************************************
 * Project Name		[JavaEE_JDBC]
 * File Name     	[DynamicProxyConnection.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package pool.dynamicProxyDataSource;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class DynamicProxyConnection implements InvocationHandler {

	private Connection realConnection; // 真正的连接
	private Connection proxyConnection; // 代理类生成的连接

	private int maxUsedNumber = 10;
	private int currentUsedNumber = 0;

	private DynamicProxyDataSource pool;

	public DynamicProxyConnection(DynamicProxyDataSource pool) {
		this.pool = pool;
	}

	/**
	 * 将真正的连接绑定到代理连接
	 * 
	 * @param realConnection
	 * @return
	 */
	public Connection bind(Connection realConnection) {
		this.realConnection = realConnection;
		this.proxyConnection = (Connection) Proxy.newProxyInstance(this.realConnection.getClass().getClassLoader(),
				new Class[] { Connection.class }, this);
		return proxyConnection;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object obj = null;

		if ("close".equalsIgnoreCase(method.getName())) {
			this.currentUsedNumber++;

			if (this.currentUsedNumber < this.maxUsedNumber) {
				this.pool.releaseConnection(this.proxyConnection);
			} else {
				this.realConnection.close();
				this.pool.currentConnectionNumber--;
			}
		} else {
			// 除了close之外的操作都有realConnection实现
			obj = method.invoke(this.realConnection, args);
		}
		return obj;
	}
}
